﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace com.ReinforceLab.AudioModem
{
    public class RawDataPacketSource : IPacketSource
    {
        #region Variables
        readonly Queue<byte[]> _sendQueue;
        readonly Queue<byte[]> _receiveQueue;
        readonly byte[] _emptyByteArray;
        #endregion

        #region Constructor
        public RawDataPacketSource()
        {
            _sendQueue = new Queue<byte[]>();
            _receiveQueue = new Queue<byte[]>();
            _emptyByteArray  = new byte[] { };
        }
        #endregion

        #region Public method
        public void Write(byte[] data)
        {
            if (data == null) return;
            _sendQueue.Enqueue(data);            
        }
        public byte[] Read()
        {
            if (_receiveQueue.Count <= 0)
                return _emptyByteArray;
            
            return _receiveQueue.Dequeue();
        }       
        #endregion

        #region IPacketSource メンバ
        public void ReceivePacket(byte[] packet, int validLength)
        {
            var data = new byte[validLength];
            packet.CopyTo(data, 0);
            _receiveQueue.Enqueue(data);            
        }
        public byte[] SendPacket(out int validLength)
        {
            if (_sendQueue.Count <= 0)
            {
                validLength = 0;
                return _emptyByteArray;
            }
            else
            {
                var data = _sendQueue.Dequeue();
                validLength = data.Length;
                return data;
            }
        }
        #endregion
    }
}
